package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;

import wsepForum.common.elements.Message;
import wsepForum.common.elements.Section;
import wsepForum.common.elements.Topic;
import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongElementIDException;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;
import javax.swing.JScrollPane;

public class EditorPanel extends AInnerPanel {
	
	private static final long serialVersionUID = 1L;
	
	private JTextField textHeader;
	private JTextArea textBody;
	private Message message;
	private JButton btnPost;
	private JScrollPane scrollPane;
	
	private int elementID;
	private ActionType actionType;
	
	private static enum ActionType { CREATE_NEW_TOPIC, NEW_MSG_ON_TOPIC, REPLY_MSG, EDIT_MESSAGE};

	
	public EditorPanel(AOuterPanel oPanel, Message message) {
		this(oPanel);
		this.message = message;
		this.elementID = this.message.getParentID();
		this.textHeader.setText(this.message.getHeadLine());
		this.textBody.setText(this.message.getBody());
		this.btnPost.setText("Save");
		this.actionType = ActionType.EDIT_MESSAGE;
	}

	public EditorPanel(AOuterPanel oPanel, Topic topic, Message message) {
		this(oPanel);
		this.message = message;
		this.elementID = topic.getElementID();
		this.textHeader.setText("RE:"+this.message.getHeadLine());
		this.textBody.setText((message.getUserName() != null ? message.getUserName() : "Guest")
				+ " says:\n" + this.message.getBody() +	"\n-------------\n");
		this.actionType = ActionType.REPLY_MSG;
	}

	public EditorPanel(AOuterPanel oPanel, Section section) {
		this(oPanel);
		this.elementID = section.getElementID();
		this.actionType = ActionType.CREATE_NEW_TOPIC;
	}

	public EditorPanel(AOuterPanel oPanel, Topic topic) {
		this(oPanel);
		this.elementID = topic.getElementID();
		this.actionType = ActionType.NEW_MSG_ON_TOPIC;
	}



	/**
	 * @wbp.parser.constructor
	 */
	public EditorPanel(AOuterPanel oPanel) {
		super(oPanel);
		setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		JLabel lblMessageEditor = new JLabel("Message Editor");
		lblMessageEditor.setHorizontalAlignment(SwingConstants.CENTER);
		lblMessageEditor.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblMessageEditor.setBounds(240, 11, 235, 31);
		add(lblMessageEditor);

		JLabel lblHeadline = new JLabel("Headline:");
		lblHeadline.setHorizontalAlignment(SwingConstants.RIGHT);
		lblHeadline.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblHeadline.setBounds(58, 45, 89, 24);
		add(lblHeadline);

		JLabel lblMessage = new JLabel("Message:");
		lblMessage.setHorizontalAlignment(SwingConstants.RIGHT);
		lblMessage.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblMessage.setBounds(58, 78, 89, 24);
		add(lblMessage);

		textHeader = new JTextField();
		textHeader.setBounds(157, 48, 402, 20);

		add(textHeader);
		textHeader.setColumns(10);
			
		textBody = new JTextArea();
		scrollPane = new JScrollPane(textBody);
		scrollPane.setBounds(157, 87, 402, 237);
		add(scrollPane);


		btnPost = new JButton("Post");
		btnPost.setBounds(468, 334, 91, 23);
		btnPost.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						btnPost.setEnabled(false);
						AInnerPanel returnedPanel = EditorPanel.this;
						if (!textHeader.getText().isEmpty() && !textBody.getText().isEmpty()) {
							GUIAnswer ans;
							switch (actionType) {
							case EDIT_MESSAGE:
								ans = request(RequestType.EDIT_MESSAGE,new Object[] {elementID,message.getElementID(),textHeader.getText(),textBody.getText()});
								outerPanel.setNumOfConnected(ans.getNumOfConnected());
								if (ans.getAnswerType().equals(AnswerType.ANSWER)) {
									ans = request(RequestType.GET_TOPIC,new Object[] { elementID });
									outerPanel.setNumOfConnected(ans.getNumOfConnected());
									if (ans.getAnswerType().equals(AnswerType.ANSWER)) {
										returnedPanel = new TopicViewPanel((Topic) ans.getArguments()[0],outerPanel);
									} else {
										returnedPanel = handlePostExceptions((Exception) ans.getArguments()[0]);
									}
								} else {
									returnedPanel = handlePostExceptions((Exception) ans.getArguments()[0]);
								}
								break;
							case NEW_MSG_ON_TOPIC:
							case REPLY_MSG:
								ans = request(RequestType.ADD_TO_TOPIC,new Object[] {elementID,textHeader.getText(),textBody.getText() });
								outerPanel.setNumOfConnected(ans.getNumOfConnected());
								if (ans.getAnswerType().equals(AnswerType.ANSWER)) {
									ans = request(RequestType.GET_TOPIC,new Object[] { elementID });
									outerPanel.setNumOfConnected(ans.getNumOfConnected());
									if (ans.getAnswerType().equals(AnswerType.ANSWER)) {
										returnedPanel = new TopicViewPanel((Topic) ans.getArguments()[0],outerPanel);
									} else {
										returnedPanel = handlePostExceptions((Exception) ans.getArguments()[0]);
									}
								} else {
									returnedPanel = handlePostExceptions((Exception) ans.getArguments()[0]);
								}
								break;
							case CREATE_NEW_TOPIC:
								ans = request(RequestType.CREATE_TOPIC,new Object[] {elementID,textHeader.getText(),textBody.getText()});
								outerPanel.setNumOfConnected(ans.getNumOfConnected());
								if (ans.getAnswerType().equals(AnswerType.ANSWER)) {
									returnedPanel = new TopicViewPanel((Topic) ans.getArguments()[0],outerPanel);
								} else {
									returnedPanel = handlePostExceptions((Exception) ans.getArguments()[0]);
								}
								break;
							}
						}
						else {
							JOptionPane.showMessageDialog(null, "message hadeline and body must not be empty!");
							btnPost.setEnabled(true);
						}
						return returnedPanel;
					}

					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handlePostExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handlePostExceptions(e));
						}
					}
					
					private AInnerPanel handlePostExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongElementIDException e) {
							JOptionPane.showMessageDialog(null, "the topic you are trying to post in was deleted by another user", "Topic deleted",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "you are not authorized to do that", "Unauthorized use",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed!\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return EditorPanel.this;
						}
					}
				};
				worker.execute();
			}
		});
		add(btnPost);
	}

}
